from flask import Flask, request

from src.day11.log_util import logger

# 实例化一个app

app = Flask(__name__)


# 定义路由 定义视图函数

@app.route("/login", methods=["post"])
def login():
    """
    登录接口，post的form演示
    :return:
    """
    # 储存form 到requets_obj 中
    requets_obj = request.form
    logger.info(f"接收到的用户输入信息是{requets_obj}")
    name = requets_obj.get("username")
    password = requets_obj.get("passwd")
    logger.info(f"登录的信息为：用户名{name},密码为{password}")
    return {"code": 0, "msg": "用户登录成功"}


@app.route("/register", methods=["post"])
def register():
    """
    注册接口,演示 json数据的获取
    :return:
    """
    # 储存json数据到requets_obj
    requets_obj = request.json
    logger.info(f"接收到的用户输入信息是{requets_obj}")
    name = requets_obj.get("username")
    password = requets_obj.get("passwd")
    passwd_confirm = requets_obj.get("passwd_confirm")
    email = requets_obj.get("email")
    logger.info(f"登录的信息为：用户名{name},密码为{password},确认密码为{passwd_confirm},邮箱为{email}")
    return {"code": 0, "msg": "用户注册成功"}


@app.route("/file", methods=["post", "get"])
def save_file():
    """
    文件处理接口，演示文件的上传，和  method的处理
    :return:
    """
    # 如果请求的类型是get，则直接返回
    if request.method == "GET":
        return {"code": 0, "msg": "文件查看成功"}
    # 不是get，则接收文件数据，进行保存
    file = request.files
    logger.info(f"file_obj is {file}")
    file_stream = file.get("file")
    logger.info(f"文件内容{file_stream}")
    file_stream.save("data.txt")
    return {"code": 0, "msg": "文件上传成功"}


@app.route("/login/users", methods=["get"])
def users():
    """
    用户信息列表查看，演示get方法
    :return:
    """
    requets_obj = request
    logger.info(f"接收到的用户输入信息是{requets_obj.args}")
    if requets_obj.args.get("a") == str(1):
        return {"code": 0, "msg": "查询a信息为1的登录用户信息成功"}
    return {"code": 0, "msg": "查询登录用户成功"}


if __name__ == '__main__':
    app.run()